<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2018/3/27
 * Time: 0:38
 */

namespace App\Services;




use App\Exception\TokenHasExpireException;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

/**
 * ͨ���ӿ�Զ�̻�ȡ�û�
 * Class UserInfoService
 * @package App\Services
 */
class UserInfoService
{
    private $client;
    private $X_CLIENT_ID;
    private $apis=[
        'getUser'=>'app-mp/user/1.0/findUserInfo',
    ];
    
    public function __construct()
    {
        $config = config('car.api_config');
        $host=$config['host'];
        
        
        $this->client = new Client(['base_uri'=>$host,'timeout'  => 3.0]);
        
    }
    
    public function getCurrentUser($user_token)
    {
        if(env('APP_ENV') == 'local'){
            $user_id = str_random(8);
            return [
                'user_id'=>$user_id,
                'nickname'=>randomNickname(),
                'avatar'=>gravatar($user_id),
            ];
        }
        
        $response = $this->client->get($this->apis['getUser'],[
            'query'=>[
                'x-client-id'=>$this->X_CLIENT_ID,
                'timestamp'=>getMillisecond(),
                'token'=>$user_token,
            ],
        ]);
        $body = json_decode((string)$response->getBody(),true);
    
        if(env('APP_DEBUG'))
            Log::info('request user:'.json_encode(['user_token'=>$user_token,'body'=>$body]));
        //dd($body);
        
        if(!\is_array($body) || !array_key_exists('data',$body) || !\is_array($body['data']['user'])){
            if(env('APP_DEBUG'))
                Log::error('request user error:'.json_encode(['user_token'=>$user_token,'body'=>$body]));
            
            throw_if(array_key_exists('code',$body) && $body['code']==14101,TokenHasExpireException::class);
            
        }
        return [
            'user_id'=>$body['data']['user_info']['user_id'],
            'nickname'=>$body['data']['user']['nick_name']?:$body['data']['user_info']['user_id'],
            'avatar'=>$body['data']['user']['photo_url']?:defaultAvatar(),
        ];
    }
    
    
    
}